#coding:utf-8

import time
import os
import socket
import ujson 
import network
from machine import Pin;
import udp_json_msg_def as UTILPRO
LOCAL_LISTEN_PORT_UDP=6667
# p13 = Pin(13, Pin.OUT)    # create output pin on GPIO0
led_i=0
addr_list={}
#------------server var----------------
udp_server_address=None
local_ip_str=""
def udp_server_init(local_ip):
    print("udp bind ip->"+local_ip+"port="+str(LOCAL_LISTEN_PORT_UDP))
    if local_ip != "":
        udp_server_address=(local_ip,LOCAL_LISTEN_PORT_UDP)
    else:
        udp_server_address=('127.0.0.1',LOCAL_LISTEN_PORT_UDP)
        
    udp_server_skt=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_server_skt.bind(udp_server_address)
    udp_server_skt.setblocking(False)
    return udp_server_skt;
def parse_udp_recv_data(udp_data):
    try:
        print("udp_data-->:")
        print(udp_data.decode())
        json_to_dict = ujson.loads(udp_data.decode())
        print(json_to_dict["hd"])
        print(json_to_dict["ver"])
        print(json_to_dict["ip"])
        print(json_to_dict["port"])
        #解析命令
        if json_to_dict[UTILPRO.K_HEAD] == UTILPRO.K_HEAD and json_to_dict[UTILPRO.K_VER] == UTILPRO.KV_VER:
            if json_to_dict["ip"] != "" and json_to_dict["port"] != 0:
                seft_ip_str = "255.255.255.255"
                seft_ip_port = 9999
                print("cmd %s" % (json_to_dict[UTILPRO.K_CMD]))
                if json_to_dict[UTILPRO.K_CMD] == UTILPRO.KC_SCAN_R:
                    print("found a dev")
                elif json_to_dict[UTILPRO.K_CMD] == UTILPRO.KC_SET_R:
                    print("set a dev ok")
                elif json_to_dict[UTILPRO.K_CMD] == UTILPRO.KC_GET_R:
                    print("get a dev ok")
                
    except:
        print("recv data err="+udp_data)
    
def udp_server_recv(skt):
    # while 1:
    # print("recv poll")
    try:        
        data,addr=skt.recvfrom(2048)
        print( "got data from",addr)
        # print (data)
        parse_udp_recv_data(data)
    except:
        pass
        # print(KeyError)
def  udp_target_add_list_init():
    #获取本地的ip地址
    for i in (network.AP_IF, network.STA_IF):
            global local_ip_str
            iface = network.WLAN(i)
            if iface.active() :
                print("ip addr on ws://%s,i=%d" % (iface.ifconfig()[0], i))
                if i == 0:
                    local_ip_str = str(iface.ifconfig()[0])
                    print("local ip="+ local_ip_str)
                    # 生成网络ip
                    add_ip_pre = local_ip_str[0:local_ip_str.rfind(".")+1];
                    for i in  range(1,255):
                        addr_ip = add_ip_pre+str(i);
                        # print(addr_ip)
                        try:
                            if addr_ip == local_ip_str:
                                print("except self ip addr")
                        except:
                            continue
                        addr_list[i]=addr_ip
                        print("ip="+str(i)+"----"+addr_list[i])
                    print("addr_list len="+ str(len(addr_list)))

def  send_udp_msg(ip_addr, port, data_msg):        
    addr_target=(ip_addr,port) 
    sock_t=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock_t.sendto((data_msg).encode(), addr_target)
    sock_t.close()

def  main_poll():
    udp_target_add_list_init()
    # skt_t = udp_server_init(local_ip_str)
    index_t = 1;
    try:
        while True:
            # udp_server_recv(skt_t);
            time.sleep(0.2);
    except KeyboardInterrupt:
        pass
    # skt_t.close()
if __name__ == '__main__':
    main_poll();
